package com.ihome.android.market2.asynctask;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ihome.android.ActivityMgr;
import com.ihome.android.EAApp;
import com.ihome.android.academy.InitialActivity;
import com.ihome.android.academy.db.UpdateApp;
import com.ihome.android.academy.db.UpdateAppInfo;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.dl.util.DownloadUtils;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.market2.view.DownloadDialog;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 获取应用升级列表
 * 
 * @author Emerson
 * 
 */
public class CheckMarketUpdateTask extends AsyncTask<String, Integer, Bundle> {
	private final String		TAG	= CheckMarketUpdateTask.class.getSimpleName();
	private Context				context;
	private List<UpdateAppInfo>	updateAppList;
	private String info ;

	public CheckMarketUpdateTask(Context context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Bundle doInBackground(String... params) {
		String appList = params[0];
		info = appList;
		LogUtil.v(TAG, "appList = " + appList);
		if (TextUtils.isEmpty(appList)) {
			return null;
		}

		Bundle b = new Bundle();
		try {
			String result = new HttpActions(context).checkMarketUpdate(appList);
			LogUtil.v(TAG, "result = " + result);
			if (!TextUtils.isEmpty(result)) {
				updateAppList = JsonAnalytic.getInstance().anslyseMarketUpdateAppResult(result);
			}
			else {
				String[] msg1 = { "", "", "" , "", "appkey", "" };
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STOREUPDATE_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
				cancel(true);
			}
		} catch (ITVException e) {
			e.printStackTrace();
			LogUtil.e(TAG, e.getMessage());
			b.putInt(HttpKeys.KEY_CODE, e.getStatusCode());
			b.putString(HttpKeys.KEY_DESCRIPTION, e.getMessage());
			String[] msg1 = { "", "", "" , "", "appkey", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STOREUPDATE_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
		}
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);

		
		if (result.containsKey(HttpKeys.KEY_CODE) && context instanceof Activity) {
			if(ITVException.HTTP_GET_HTTP_URL_CONN_IO_EXCEPTION == result.getInt(HttpKeys.KEY_CODE)){
				DialogFactory.onBtnClickListener don = new onBtnClickListener() {
					public void btnRightClickListener(View v) {
						String[] msg = {"","","","","",""};
						UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
						EAApp.getApp().exitApp(true);
					}

					public void btnNeutralClickListener(View v) {


					}

					public void btnLeftClickListener(View v) {
						new CheckMarketUpdateTask(context).execute(info);
					}

					@Override
					public void btnCloseClickListener(View v) {

					}
				};
				new DialogFactory(context).showDialog2Btn(context.getString(R.string.attention_error), result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")","重试","取消",don);
			}else{
				if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE)){
					new DialogFactory(context).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",context.getString(R.string.dialog_ok),new onBtnClickListener() {
						
						@Override
						public void btnRightClickListener(View v) {
							// TODO Auto-generated method stub
							EAApp.getApp().exitApp(true);
						}
						
						@Override
						public void btnNeutralClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnLeftClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnCloseClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
					});
					return;
				}
				DialogFactory.onBtnClickListener don = new onBtnClickListener() {
					public void btnRightClickListener(View v) {
						String[] msg = {"","","","","",""};
						UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
						EAApp.getApp().exitApp(true);
					}

					public void btnNeutralClickListener(View v) {


					}

					public void btnLeftClickListener(View v) {
						String[] msg = {"","","","","",""};
						UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
						EAApp.getApp().exitApp(true);
					}

					@Override
					public void btnCloseClickListener(View v) {

					}
				};
				new DialogFactory(context).showDialog(context.getString(R.string.attention_error),result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")","",don);
			}
			return;
		}
		
		if (updateAppList != null && updateAppList.size() > 0) {
			for (int i = 0, len = updateAppList.size(); i < len; i++) {
				UpdateAppInfo updateApp = updateAppList.get(i);
				LogUtil.d(TAG, "updateApp = " + updateApp.toString());

				if (updateApp.pkgName.equals(context.getPackageName())) {
					checkMarketUpdate(updateApp);
				}
				updateApp.version = Util.getAPKVersion(context);
				UpdateApp.updateInsert(context, updateApp);
			}
		}
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");

	}

	private void checkMarketUpdate(final UpdateAppInfo updateApp) {

		try {
			Context mContext = ActivityMgr.getInstance().peek();
			if (context == null || !(mContext instanceof InitialActivity) || ((InitialActivity) context).isFinishing()) {
				LogUtil.e(TAG, "--> InitialActivity isFinishing ");
				context = mContext;
			}
		} catch (Exception e) {
			String[] msg1 = { "", "", "" , "", "appkey", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STOREUPDATE_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg1);
			e.printStackTrace();
			return;
		}

		UpdateAppInfo marketInfo = UpdateApp.getUpdateAppByPkgName(context, context.getPackageName());
		if (marketInfo != null && marketInfo.isUpdate) {
			LogUtil.v(TAG, "market = \n" + marketInfo.toString());
			try {
				JSONArray element = new JSONArray();
				JSONObject item = new JSONObject();
				item.put("pkgName", marketInfo.pkgName);
				item.put("newVersion", updateApp.version);
				item.put("oldVersion", marketInfo.version);
				if (!updateApp.isUpdate) {
					// market update successfully
					item.put("result", "0");
				}
				else {
					// market update failure
					item.put("result", "1");
				}
				if (!TextUtils.isEmpty(item.optString("pkgName"))) {
					element.put(item);
					new UpdateResultReportTask(context).execute(element.toString());
				}

			} catch (JSONException e) {
				String[] msg1 = { "", "", "" , "", "appkey", "" };
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STOREUPDATE_EXCEPTION, NotifyType.TYPE_EXCEPTION, "", msg1);
				e.printStackTrace();
			}
		}

		// market update begin
		if (updateApp.isUpdate) {
			if (TextUtils.isEmpty(updateApp.url)) {
				String[] msg1 = { "", "", "" , "", "", "" };
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STOREUPDATE_EXCEPTION, NotifyType.TYPE_EXCEPTION, "", msg1);
				return;
			}

			LogUtil.v(TAG, "To DownloadDialog ....");
			//			new DownloadDialog(context, updateApp.fileName, updateApp.url,updateApp.pkgName,"").show();
			String content = context.getString(R.string.update_market);
			new DialogFactory(context).showDialog(context.getString(R.string.update_tip), content,  context.getString(R.string.update_imme), new onBtnClickListener() {

				@Override
				public void btnLeftClickListener(View v) {
					if(!DownloadUtils.isNetworkAvailable(context)){

						String[] msg1 = { "", "", "" , "", "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.NETWORK_EXCEPTION, NotifyType.TYPE_EXCEPTION, "", msg1);
						
						new DialogFactory(context).showDialog(context.getString(R.string.attention_error), context.getString(R.string.check_current_network), "", new onBtnClickListener() {
							@Override
							public void btnRightClickListener(View v) {
								String[] msg = {"","","","","",""};
								UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
								EAApp.getApp().exitApp(true);								
							}

							@Override
							public void btnNeutralClickListener(View v) {
								String[] msg = {"","","","","",""};
								UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
								EAApp.getApp().exitApp(true);
							}

							@Override
							public void btnLeftClickListener(View v) {
								String[] msg = {"","","","","",""};
								UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
								EAApp.getApp().exitApp(true);
							}

							@Override
							public void btnCloseClickListener(View v) {
								String[] msg = {"","","","","",""};
								UserBehaviorLog.getInstance().writeLog(UserBehavior.LOGOUT, NotifyType.TYPE_NORMAL, "", msg);
								EAApp.getApp().exitApp(true);
							}
						});
						return;
					}
					new DownloadDialog(context, updateApp.fileName, updateApp.url,updateApp.pkgName,"").show();

				}

				@Override
				public void btnNeutralClickListener(View v) {

				}

				@Override
				public void btnRightClickListener(View v) {

				}

				@Override
				public void btnCloseClickListener(View v) {

				}

			});

		}else{
			((InitialActivity) context).toLogin();
		}
	}

}
